using B.S.XZYData.Api.Read.Application.Command.Route;
using B.S.XZYData.Api.Read.Dto.Route;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Route
{
    /// <summary>
    /// 根据工艺路线ID查询工序信息处理器
    /// </summary>
    public class GetRouteStepsHandler : IRequestHandler<GetRouteStepsCommand, ApiResult<List<RouteStepDto>>>
    {
        private readonly IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> _processRepository;
        private readonly IMapper _mapper;

        public GetRouteStepsHandler(IBaseRepository<B.S.XZYData.Domain.ZSHH.Process> processRepository, IMapper mapper)
        {
            _processRepository = processRepository;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<RouteStepDto>>> Handle(GetRouteStepsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<RouteStepDto>>();

            try
            {
                // 先查询所有工序数据用于调试
                var allProcesses = _processRepository.GetAll().ToList();
                
                // 根据工艺路线ID查询工序信息
                var processes = _processRepository.GetAll()
                    .Where(x => x.RoutdId == request.RouteId)
                    .OrderBy(x => x.ProcessNumber)
                    .ToList();

                // 使用AutoMapper映射为DTO
                var stepDtos = _mapper.Map<List<RouteStepDto>>(processes);

                result.Data = stepDtos;
                result.Code = ApiEnum.Success;
                result.Msg = stepDtos.Count > 0 
                    ? "查询工序信息成功" 
                    : $"该工艺路线暂无工序信息。总工序数：{allProcesses.Count}，请求路线ID：{request.RouteId}";
            }
            catch (AutoMapperMappingException ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"查询工序信息失败：映射异常 -> {ex.Message}";
                result.Data = new List<RouteStepDto>();
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Error;
                result.Msg = $"查询工序信息失败：{ex.Message}";
                result.Data = new List<RouteStepDto>();
            }

            return result;
        }
    }
}
